package ucap.com.lesanapp.view;

import android.content.Context;
import android.content.pm.PackageManager;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import ucap.com.lesanapp.R;
import ucap.com.lesanapp.base.BaseDialog;
import ucap.com.lesanapp.bean.UpdateBean;
import ucap.com.lesanapp.global.Constants;

/**
 * Created by wekingwang on 16/10/17.
 */

public class LodingDialog extends BaseDialog {
    protected LodingDialog(Context context) {
        super(context);
    }

    public static void showDialog(Context ctx) {
        LodingDialog dialog = new LodingDialog(ctx);
        dialog.setCancelable(false);
        dialog.show();
    }

    @Override
    public void setView() {
        setContentView(R.layout.dialog_loading);
    }

    @Override
    public void setListener() {

    }

    @Override
    public void setData() {
        HttpUtils utils = new HttpUtils();
        utils.send(HttpMethod.GET, Constants.URL_UPDATE, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                UpdateBean updateBean = gson.fromJson(responseInfo.result, UpdateBean.class);
                int version = Integer.parseInt(updateBean.getVersion());
                if (isUpdate(version)) {//检查是否又更新
                    UpDateDialog.showDialog(getContext(), updateBean.getVersion(), updateBean.getName(), updateBean.getSm(), updateBean.getPath());
                } else {
                    Toast.makeText(getContext(), "已是最新版！", Toast.LENGTH_SHORT).show();
                }
                dismiss();
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Toast.makeText(getContext(), "连接错误！", Toast.LENGTH_LONG).show();
                dismiss();
            }
        });
    }

    /**
     * h获取本地版本号
     *
     * @param code
     * @return
     */
    private boolean isUpdate(int code) {
        try {
            int packageCode = getContext().getPackageManager().getPackageInfo(getContext().getPackageName(), PackageManager.GET_CONFIGURATIONS).versionCode;
            if (packageCode < code) {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public void setClick(View v) {

    }
}
